package com.ruoyi.project.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.juhe.sdk.ApiClient;
import com.juhe.sdk.common.Result;
import com.juhe.sdk.reqeust.EnterpriseTaxQueryRequest;
import com.juhe.sdk.response.BankCardHVerifyResponse;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.domain.dto.ThrEleResult;
import com.ruoyi.project.system.domain.po.TaxInfo;
import com.ruoyi.project.system.domain.vo.ProductQueryOrder;
import com.ruoyi.project.system.domain.vo.QueryPaysVo;
import com.ruoyi.project.system.domain.vo.QueryVo;
import com.ruoyi.project.system.domain.vo.Record;
import com.ruoyi.project.system.mapper.SmPayMapper;
import com.ruoyi.project.system.mapper.SmProductMapper;
import com.ruoyi.project.system.mapper.SmQueryMapper;
import com.ruoyi.project.system.mapper.SmTaxMapper;
import com.ruoyi.project.system.service.ISmQueryService;
import com.ruoyi.project.system.service.SmSMSService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import static com.ruoyi.common.constant.CacheConstants.RUN_PARAM;
import static com.ruoyi.common.utils.http.HttpUtils.sendPost;
import static com.ruoyi.project.utils.SmHandler.handleTaxes;

/**
 * 查询进件Controller
 */
@Slf4j
@RestController
@RequestMapping("/system/query")
public class SmQueryController extends BaseController {

    @Autowired
    private ISmQueryService smQueryService;

    @Autowired
    private SmSMSService smSMSService;

    @Autowired
    private SmQueryMapper smQueryMapper;

    @Autowired
    private SmProductMapper smProductMapper;

    @Autowired
    private SmPayMapper smPayMapper;

    @Autowired
    private SmTaxMapper smTaxMapper;

    @Autowired
    private RedisCache redisCache;

    ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");

    private static final Logger logger = LoggerFactory.getLogger("stacktrace_info");

    /**
     * 新增查询进件
     */
    @Anonymous
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SmQuery smQuery) {
        String isThrEle = smProductMapper.selectIsThrEle(smQuery.getProductId());
        if (StringUtils.isEmpty(isThrEle)) {
            return error("参数异常！");
        } else if ("1".equals(isThrEle)) {
            if (StringUtils.isEmpty(smQuery.getName()) ||
                    StringUtils.isEmpty(smQuery.getCardNo()) ||
                    StringUtils.isEmpty(smQuery.getTel())) {
                return error("缺少参数！");
            }
            ThrEleResult thrEleResult = smQueryService.verificationThrEle(new SmAutonomy(smQuery));
            smQueryMapper.insertAutonomy(thrEleResult.getSmAutonomy());
            if (!thrEleResult.isPass()) {
                return warn(thrEleResult.getMsg());
            }
        }
        smQueryService.insertSmQuery(smQuery);
        return success(smQuery.getId());
    }

    /**
     * 即时查询项目
     */
    @Anonymous
    @GetMapping("/data")
    public AjaxResult query(@NotBlank(message = "没有单号") String orderNo) {
        SmPay smPay = smPayMapper.selectPayByOrderNo(orderNo);
        if (smPay == null) {
            return error("无支付记录！");
        } else if ("SUCCESS".equals(smPay.getPayState())) {
            int validDayNum = redisCache.getCacheObject(RUN_PARAM + "validDayNum");
            LocalDateTime validTime = LocalDateTime.ofInstant(smPay.getPayTime().toInstant(), ZoneId.systemDefault()).plusDays(validDayNum);
            String endTime = validTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (LocalDateTime.now().isAfter(validTime)) {
                return warn("查询订单已过有效期").put("endTime", endTime);
            }
            SmQuery smQuery = smQueryService.selectSmQueryById(smPay.getOutId());
            return smQueryService.getAjaxResult(smQuery, endTime);
        } else if ("NOTPAY".equals(smPay.getPayState())) {
            return warn("查询订单未支付！");
        } else if ("REFUND".equals(smPay.getPayState())) {
            return warn("查询订单已退款！");
        } else {
            return warn("查询订单异常！");
        }
    }

    /**
     * 即时查询项目
     */
    @GetMapping("/dataById")
    public AjaxResult dataById(@NotNull(message = "没有单号") Integer id) {
        SmQuery smQuery = smQueryService.selectSmQueryById(id);
        return smQueryService.getAjaxResult(smQuery, "");
    }

    /**
     * 获取企业纳税查询授权URL
     */
    @Anonymous
    @GetMapping("/taxesAuthUrl")
    public AjaxResult taxesAuthUrl(SmQuery smQuery) {
        if (StringUtils.isEmpty(smQuery.getTel()) || smQuery.getTel() == null) {
            return warn("缺少参数");
        }
        try {
            JSONObject response = smQueryService.companyQuery(smQuery);
            if (!"000000".equals(response.getString("retcode"))) {
                log.error("taxesAuthUrl调用出错：", response.getString("retmsg"));
                return error(response.getString("msg"));
            }
            String authUrl = response.getJSONObject("retdata").getString("authUrl");
            String taskId = response.getJSONObject("retdata").getString("taskId");
            smQuery.setProductId(3);
            smQuery.setQueryInfo(taskId);
            smQuery.setRemark(authUrl);
            smQueryMapper.insertSmQuery(smQuery);
            smTaxMapper.insertSmTax(smQuery.getId());
            return success().put("authUrl", authUrl).put("queryId", smQuery.getId());
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 轮询企业纳税获取状态
     */
    @Anonymous
    @GetMapping("/taxesStatus/{id}")
    public AjaxResult taxesStatus(@PathVariable("id") @NotNull(message = "没有单号") Integer id) {
        Tax tax = smTaxMapper.selectSmTaxByQueryId(id);
        if (tax == null) {
            String taskId = smTaxMapper.selectTaskIdByQueryId(id);
            //2.准备参数
            EnterpriseTaxQueryRequest param = new EnterpriseTaxQueryRequest();
            param.setTaskId(taskId);
            try {
                Result<BankCardHVerifyResponse> response = apiClient.queryReportResult(param);
                if (response.getCode() != 200) {
                    log.error("taxesStatus调用出错：" + response.getMsg());
                    return AjaxResult.error(202, response.getMsg());  //202
                }
                int resultCode = response.getData().getResultCode();
                smTaxMapper.updateSmTaxStatus(new Tax(id, param.getRequestId(), "" + resultCode));
                if (resultCode != 3) {
                    return AjaxResult.error(202, "状态未完成");  //202
                } else {
                    // 短信通知结果
                    String tel = smQueryService.selectSmQueryById(id).getTel();
                    smSMSService.sendTaxSuccessResult(tel, id);
                }
            } catch (Exception e) {
                log.error("调用出错: {}", e);
                return error(e.getMessage());  //501
            }
        }
        String orderNo = smTaxMapper.selectPayStatusByQueryId(id);
        if (StringUtils.isEmpty(orderNo)) {
            return AjaxResult.error(204, "获取成功，未支付");   //204
        }
        return success(orderNo);  // 200
    }

    /**
     * 获取企业纳税收集结果
     */
    @Anonymous
    @GetMapping("/taxesResult/{on}")
    public AjaxResult taxesResult(@PathVariable("on") @NotNull(message = "没有单号") String orderNo) {
        SmPay smPay = smTaxMapper.selectPayStatusByOrderNo(orderNo);
        if (smPay == null) {
            return warn("未进行支付！");
        } else if ("NOTPAY".equals(smPay.getPayState())) {
            return warn("未支付！");
        } else if ("REFUND".equals(smPay.getPayState())) {
            return warn("已退款不可见！");
        } else if ("SUCCESS".equals(smPay.getPayState())) {
            int validDayNum = redisCache.getCacheObject(RUN_PARAM + "validDayNum");
            LocalDateTime validTime = LocalDateTime.ofInstant(smPay.getPayTime().toInstant(), ZoneId.systemDefault()).plusDays(validDayNum);
            String endTime = validTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (LocalDateTime.now().isAfter(validTime)) {
                return warn("查询订单已过有效期").put("endTime", endTime);
            }
            Integer queryId = smPay.getOutId();
            TaxInfo taxInfo = smTaxMapper.selectSmTaxInfoByQueryId(queryId);
            if (taxInfo == null) {
                String taskId = smTaxMapper.selectTaskIdByQueryId(queryId);
                EnterpriseTaxQueryRequest param = new EnterpriseTaxQueryRequest();
                param.setTaskId(taskId);
                try {

                    // MGZ TODO 2025/8/2: 获取企业纳税收集结果
                    Result<com.alibaba.fastjson.JSONObject> response = apiClient.queryTaxReport(param);
                    logger.warn(queryId + "——>" + response.getData());
                    if (response.getCode() != 200) {
                        log.error("taxesResult调用出错：", response.getMsg());
                        return warn(response.getMsg());
                    } else {
                        com.alibaba.fastjson.JSONObject data = response.getData();

//                    com.alibaba.fastjson.JSONObject data = JSON.parseObject(readLine().toString());
                        for (String k : data.keySet()) {
                            if (data.containsKey(k)) {
                                Object obj = data.get(k);
                                if (obj instanceof JSONArray) {
                                    data.replace(k, data.getJSONArray(k).toJSONString());
                                } else if (obj instanceof JSONObject) {
                                    data.replace(k, data.getJSONObject(k).toJSONString());
                                }
                            }
                        }
                        taxInfo = data.toJavaObject(TaxInfo.class);
                        taxInfo.setQueryId(queryId);
                        smTaxMapper.insertSmTaxInfo(taxInfo);
                        smQueryMapper.updateSmQuery(new SmQuery(queryId, taxInfo.getCompanyName(), false));
                    }
                } catch (Exception e) {
                    log.error("调用出错: {}", e);
                    return error(e.getMessage());
                }
            }
            return success(handleTaxes(taxInfo));

        } else {
            return warn("状态异常");
        }
    }

    /**
     * 查询查询进件列表
     */
    @GetMapping("/product")
    public TableDataInfo product(Integer productId, String keyword) {
        Long userId = SecurityUtils.getUserId();

        startPage();
        List<ProductQueryOrder> list = smQueryMapper.productQueryOrders(productId, userId, keyword); // MGZ TODO 2025/4/14:产品查询记录
        return getDataTable(list);
    }

    @GetMapping("/recently")
    public AjaxResult userRecentlyIncome(String keyword, @NotNull Integer pageNum) {
        Long userId = SecurityUtils.getUserId();
        List<Integer> ids = smProductMapper.ids();
        List<ProductQueryOrder> productQueryOrders = smQueryMapper.userRecentlyQueryOrder(
                ids, userId, keyword, pageNum * 10
        );
        return success(productQueryOrders);
    }

    /**
     * 查询查询进件列表
     */
    @PreAuthorize("@ss.hasPermi('system:query:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryVo queryVo) {
        startPage();
        List<QueryVo> list = smQueryService.selectSmQueryList(queryVo);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:query:list')")
    @GetMapping("/autonomyList")
    public TableDataInfo autonomyList(SmAutonomy smAutonomy) {
        startPage();
        List<SmAutonomy> list = smQueryMapper.selectAutonomyList(smAutonomy);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:query:list')")
    @GetMapping("/smsList")
    public TableDataInfo smsList(SMSRecord smsRecord) {
        startPage();
        List<SMSRecord> list = smQueryMapper.selectSMSRecordList(smsRecord);
        return getDataTable(list);
    }

    @GetMapping("/smsPlatform")
    public AjaxResult smsPlatform(@NotBlank String sendId) {
        JSONObject object = JSONObject.parseObject("{\"send_id\": \"c271c87905a04ebb658e1d380cb3abc8\",\"signature\": \"a723473e64368a399df52cac7b2727ab\",\"appid\": \"109643\"}");
        object.replace("send_id", sendId);
        String sendPost = sendPost("https://api-v4.mysubmail.com/sms/log.json", object);
        return success(JSON.parseObject(sendPost));
    }

    @GetMapping("/teamList")
    public TableDataInfo teamList(SmQuery smQuery) {
        smQuery.setUserId(SecurityUtils.getUserId());
        startPage();
        List<QueryPaysVo> list = smQueryMapper.teamQueryList(smQuery);

        for (QueryPaysVo sq : list) {
//            if (StringUtils.isNotEmpty(sq.getName())) {
//                sq.setName("**" + sq.getName().substring(1));
//            }
            if (StringUtils.isNotEmpty(sq.getCardNo())) {
                sq.setCardNo("******" + sq.getCardNo().substring(6));
            }
            if (StringUtils.isNotEmpty(sq.getTel())) {
                sq.setTel("*******" + sq.getTel().substring(7));
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询进件记录列表
     */
    @Anonymous
    @GetMapping("/recordList")
    public List<Record> recordList(String mobile, String sign) {
        // 拉取数据
        return smQueryService.getRecords(mobile, sign);
    }

    /**
     * 查询进件记录列表通过手机号
     */
    @Anonymous
    @GetMapping("/recordListByMobile")
    public AjaxResult recordListByMobile(String mobile, String code) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + mobile;
        String captcha = redisCache.getCacheObject(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            return AjaxResult.error(4002, "验证码失效");
        }
        redisCache.deleteObject(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(code, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 拉取数据
        return AjaxResult.success(smQueryService.getRecords(mobile, null));
    }

    /**
     * 获取查询进件详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:query:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(smQueryService.selectSmQueryById(id));
    }

    /**
     * 修改查询进件
     */
    @PreAuthorize("@ss.hasPermi('system:query:edit')")
    @Log(title = "查询进件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SmQuery smQuery) {
        return toAjax(smQueryService.updateSmQuery(smQuery));
    }

    /**
     * 删除查询进件
     */
    @PreAuthorize("@ss.hasPermi('system:query:remove')")
    @Log(title = "查询进件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(smQueryService.deleteSmQueryByIds(ids));
    }
}
